<template>
  <PageWrapper contentFullHeight fixedHeight contentClass="main-box">
    <BasicFormForBOE class="search-box" @register="register" @submit="getChartData" v-loading="loading">
      <template #deviceId1="">
        <TreeSelect :treeData="treeData" @change-value="handleChangeDevice1" :disabledKey="deviceId2" :index="1">
        </TreeSelect>
      </template>
      <template #deviceId2="">
        <TreeSelect :treeData="treeData" @change-value="handleChangeDevice2" :disabledKey="deviceId1" :index="2">
        </TreeSelect>
      </template>
    </BasicFormForBOE>
    <div class="content-box">
      <BasicBOETitle title="设备能耗对比">
        <BasicTable @register="registerTable">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <TableAction :actions="createActions(record)" />
            </template>
          </template>
        </BasicTable>
      </BasicBOETitle>
      <BasicBOETitle title="对标分析">
        <Bar v-if="chartData" class="chart" :loading="chartLoading" :chartData="chartData" />
        <a-empty v-else :image="simpleImage" />
      </BasicBOETitle>
    </div>
  </PageWrapper>
</template>
<script setup lang="ts">
import { PageWrapper } from '@/components/Page'
import { BasicTable, useTable, TableAction, EditRecordRow, ActionItem } from '@/components/Table'
import { searchFormSchema, columns } from './data'
import { ref, watchEffect, onMounted } from 'vue'
import { useMessage } from '@/hooks/web/useMessage'
import { BasicFormForBOE, useForm, } from '@/components/Form';
import { Empty } from 'ant-design-vue';
import BasicBOETitle from '@/components/Basic/src/BasicBOETitle.vue'
import { getClassifyTree } from '@/api/collection/classify'
import { getCompareChartData } from '@/api/energyCompare/deviceConsumptionCompare'
import TreeSelect from './TreeSelect.vue'
import Bar from '@/components/Charts/Bar/index.vue'

const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;

defineOptions({ name: 'BudgetData' })
const { createMessage: msg } = useMessage()
const loading = ref(false)
const currentEditKeyRef = ref('')
const treeData = ref([])
const dataSource = ref([])
const deviceId1 = ref()
const deviceId1NodeData = ref()
const deviceId2 = ref()
const deviceId2NodeData = ref()
const chartLoading = ref(false)
const chartData = ref()
let initGetData = false
const [register, { getFieldsValue }] = useForm({
  labelWidth: 80,
  schemas: searchFormSchema,
  autoSubmitOnEnter: true,
})
const [registerTable, { reload, setLoading, getDataSource }] = useTable({
  dataSource: dataSource,
  pagination: false,
  columns,
  useSearchForm: false,
  size: 'small',
  bordered: false,
  striped: true,
  actionColumn: {
    width: 120,
    title: '操作',
    dataIndex: 'action',
  },
})

function createActions(record: EditRecordRow): ActionItem[] {
  if (!record.editable) {
    return [
      {
        label: '编辑',
        disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.dataTypeId : false,
        onClick: handleEdit.bind(null, record),
      },
    ]
  }
  return [
    {
      label: '保存',
      onClick: handleSave.bind(null, record),
    },
    {
      label: '取消',
      onClick: handleCancel.bind(null, record),
    },
  ]
}

onMounted(() => {
  getTreeData()
})
watchEffect(() => {
  if (deviceId1.value && deviceId2.value && !initGetData) {
    initGetData = true
    getChartData()
  }
})

const formatTreeData = (data) => {
  return data.map((item) => {
    return {
      ...item,
      checkable: item.type === 1,
      children: formatTreeData(item.children),
    }
  })
}

const getTreeData = async () => {
  loading.value = true
  const data = await getClassifyTree({
    type: 1
  }).finally(() => {
    loading.value = false
  })
  treeData.value = formatTreeData(data)
}

const getChartData = () => {
  // 如果没有设备，则不要查询接口
  if (!deviceId1.value || !deviceId2.value) return
  const typeVOList = getDataSource().filter(item => !isNaN(item.standard)).map((item) => ({
    dataTypeId: item.dataTypeId,
    standard: item.standard
  }))
  const data = {
    ...getFieldsValue(),
    deviceId1: deviceId1NodeData.value.classifyId,
    deviceId2: deviceId1NodeData.value.classifyId,
    typeVOList
  }
  chartLoading.value = true
  setLoading(true)
  getCompareChartData(data).then(res => {
    const { chat, compareTypeList } = res
    chartData.value = chat
    dataSource.value = compareTypeList
  }).finally(() => {
    chartLoading.value = false
    setLoading(false)
  })
}
const handleChangeDevice1 = ({ value, nodeData }) => {
  deviceId1.value = value
  deviceId1NodeData.value = nodeData
}
const handleChangeDevice2 = ({ value, nodeData }) => {
  deviceId2.value = value
  deviceId2NodeData.value = nodeData

}
const handleCancel = (record: EditRecordRow) => {
  currentEditKeyRef.value = ''
  record.onEdit?.(false, false)
}

const handleEdit = (record) => {
  currentEditKeyRef.value = record.dataTypeId
  record.onEdit?.(true)
}

const handleSave = async (record) => {
  // 校验
  const valid = await record.onValid?.()
  if (valid) {
    getChartData()
    const pass = await record.onEdit?.(false, true)
    if (pass) {
      currentEditKeyRef.value = ''
    }
    msg.success({ content: '数据已更改', key: 'saving' })
    reload()
  } else {
    msg.error({ content: '请填写正确的数据', key: 'saving' })
  }
}

</script>
<style scoped lang="scss">
.search-box {
  margin-bottom: 8px;
  padding: 12px 10px 6px;
  border-radius: 2px;
  background-color: var(--component-background-color);

  :deep(.ant-form-item) {
    margin: 6px;
  }
}

.content-box {
  display: flex;
  flex: 1;
  flex-direction: column;
  overflow: hidden;

  .common-card {
    flex: 1;
    margin: 4px;
    overflow: hidden;
    background: #fff;

    :deep(.ant-table-wrapper) {
      padding: 0;
    }
  }
}
</style>
